package com.etc.interceptor;

import cn.hutool.json.JSONObject;
import com.etc.util.MyJWTHutool;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginHandlerInceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //request.getHeader
        String token = request.getHeader("Authorization");
        //请求头数据为空
        if(token == null) {
            //返回json，包含错误的具体信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("code",0);
            res.put("msg","尚未登录或者登录信息失效");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }



//			算法的验证包括两个方面
//			验证header中算法ID和提供的算法ID是否一致
//			调用JWT.verify验证token是否正确

        //JWTValidator jwtValidator = JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256("jjwt".getBytes()));
        boolean validate = false;
        try{
            validate = MyJWTHutool.validate(token);
        }catch (Exception ex){
            //返回json，包含错误的具体信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("code",0);
            res.put("msg","尚未登录或者登录信息失效");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }


        //扩展部分:

        //如果r验证无法通过
        if(!validate) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("code",0);
            res.put("msg","尚未登录或者登录信息失效");
            out = response.getWriter();
            out.append(res.toString());
            return false;
        }
        //验证 -=>通过
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
